package com.yingpai.fitness.dvp_2_0.main.activity.dynamic;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions2.Permission;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.base.BaseResponse;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.vip_card.MemberInfoBean;
import com.yingpai.fitness.entity.wx.TokenBean;
import com.yingpai.fitness.dvp_2_0.main.util.sensitive.SensitivewordFilter;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.functions.Consumer;


public class PublishActivity extends CommonActivity {


    @BindView(R.id.right_tv)
    TextView rightTv;
    @BindView(R.id.publishUserImg)
    CircleImageView publishUserImg;
    @BindView(R.id.publishUserNametV)
    TextView publishUserNametV;
    @BindView(R.id.publishTitleEt)
    EditText publishTitleEt;
    @BindView(R.id.publishContentEt)
    EditText publishContentEt;
    @BindView(R.id.photo_ll)
    LinearLayout photoLl;
    @BindView(R.id.addcommentImgTv)
    TextView addcommentImgTv;
    @BindView(R.id.publishAddressTv)
    TextView publishAddressTv;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private List<File> imageList;

    private int photo_num = 3;
    private LayoutInflater layoutInflater;
    private String street;
    private String flag;
    private int categoryId;
    private String categoryName;
    private String city;
    private TokenBean tokenBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.publish_activity);
    }

    @Override
    protected void initView() {
        setTitle("晒图");
        rightTv.setText("发布");

        layoutInflater = LayoutInflater.from(this);

        imageList = new ArrayList<>();

        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            flag = bundle.getString("flag");
            categoryId = bundle.getInt("categoryId", -1);
            categoryName = bundle.getString("categoryName");
        }
    }

    @Override
    protected void initData() {
        requestData();
    }

    private void requestData() {
        showDialog(this, null);
        HttpParams httpParams = new HttpParams();
        httpParams.put("customerId", tokenBean.getId());
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_INFORMATION, httpParams, Url.GET_INFORMATION, new Callback<MemberInfoBean>() {
            @Override
            public void onSuccess(MemberInfoBean memberInfoBean) {
                if (memberInfoBean.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    Glide.with(PublishActivity.this)
                            .load(memberInfoBean.getMap().getCustomer().getPhotoUrl() + "")
                            .into(publishUserImg);
                    publishUserNametV.setText(memberInfoBean.getMap().getCustomer().getNickName() == null ? "Welcome" : memberInfoBean.getMap().getCustomer().getNickName() + "");
                } else {
                    showToast(memberInfoBean.getMsg());
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });

        if (!rxPermissions.isGranted(Manifest.permission.ACCESS_FINE_LOCATION)) {
            rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean) {
                        initLocation();
                        mLocationClient.start();//重新定位
                    } else {
                        showToast("拒绝权限可能导致部分功能不能使用");
                    }
                }
            });
        } else {
            initLocation();
            mLocationClient.start();//重新定位
        }
    }

    private void initLocation() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//                Toast.makeText(this, "打开后直接点击返回键即可，若不打开返回下次将再次出现", Toast.LENGTH_SHORT).show();
            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
        }

        mLocationClient = new LocationClient(context);
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setIsNeedAddress(true);
        //是否需要地址信息 默认不需要

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(0);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
    }

    @Override
    @OnClick({R.id.right_tv, R.id.addcommentImgTv})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.right_tv:
                if (!TextUtils.isEmpty(publishContentEt.getText().toString().trim()) &&
                        !TextUtils.isEmpty(publishTitleEt.getText().toString().trim())) {
                    if (imageList.size() != 0) {
                        SensitivewordFilter filter = new SensitivewordFilter(PublishActivity.this);
                        Set<String> set = filter.getSensitiveWord(publishContentEt.getText().toString().trim() + publishTitleEt.getText().toString().trim(), 1);
                        if (set.size() > 0) {
                            showToast("您输入的内容包含敏感词");
                        } else {
                            showDialog(this, "发布中...");
                            if ("dynamic".equals(flag)) {
                                HttpParams params = new HttpParams();
                                params.put("themeTitle", publishTitleEt.getText().toString().trim());
                                params.putFileParams("files", imageList);
                                params.put("publisherId", tokenBean.getId());
                                params.put("publisherName", publishUserNametV.getText().toString());
                                params.put("publishLocale", publishAddressTv.getText().toString());
                                params.put("publishCity", city);
                                params.put("content", publishContentEt.getText().toString().trim());
                                finalOkGo.request(RequestType.POSTFILE, Contacts.HOST_SERVER + Url.PUBLISH_DYNAMIC, params, Url.PUBLISH_DYNAMIC, new Callback<BaseResponse>() {
                                    @Override
                                    public void onSuccess(BaseResponse baseResponse) {
                                        if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                            EventBus.getDefault().post("dynamic_success");
                                            finishActivity();
                                        } else {
                                            showToast(baseResponse.getMsg());
                                        }
                                        dismissDialog();
                                    }

                                    @Override
                                    public void onError(Response<String> response) {
                                        super.onError(response);
                                        dismissDialog();
                                    }
                                });
                            } else {
                                HttpParams params = new HttpParams();
                                params.put("categoryId", categoryId);
                                params.put("categoryName", categoryName);
                                params.put("themeTitle", publishTitleEt.getText().toString().trim());
                                params.putFileParams("files", imageList);
                                params.put("publisherId", tokenBean.getId());
                                params.put("publisherName", publishUserNametV.getText().toString());
                                params.put("publishLocale", publishAddressTv.getText().toString());
                                params.put("publishCity", city);
                                params.put("content", publishContentEt.getText().toString().trim());
                                finalOkGo.request(RequestType.POSTFILE, Contacts.HOST_SERVER + Url.PUBLISH_DYNAMIC, params, Url.PUBLISH_DYNAMIC, new Callback<BaseResponse>() {
                                    @Override
                                    public void onSuccess(BaseResponse baseResponse) {
                                        if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                            EventBus.getDefault().post("topic_success");
                                            finishActivity();
                                        } else {
                                            showToast(baseResponse.getMsg());
                                        }
                                        dismissDialog();
                                    }

                                    @Override
                                    public void onError(Response<String> response) {
                                        super.onError(response);
                                        dismissDialog();
                                    }
                                });
                            }
                        }
//
                    } else {
                        showToast("请填加图片");
                    }
                } else {
                    showToast("请填写评论内容");
                }
                break;
            case R.id.addcommentImgTv:
                if (rxPermissions.isGranted(Manifest.permission.CAMERA) && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    showTakePhotoOrAlbumDialog();
                } else {
                    rxPermissions.requestEach(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .subscribe(new Consumer<Permission>() {
                                @Override
                                public void accept(Permission permission) throws Exception {
                                    if (permission.granted) {
                                        // 用户已经同意该权限
                                        showTakePhotoOrAlbumDialog();
                                    } else if (permission.shouldShowRequestPermissionRationale) {
                                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                                        showToast("拒绝权限可能导致部分功能不能使用");
                                    } else {
                                        // 用户拒绝了该权限，并且选中『不再询问』
                                        showToast("拒绝权限可能导致部分功能不能使用，如果需要请在设置中修改");
                                    }
                                }
                            });
                }
                break;
        }
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
//
//            String addr = location.getAddrStr();    //获取详细地址信息
//            String country = location.getCountry();    //获取国家
//            String province = location.getProvince();    //获取省份
            //获取城市
            city = location.getCity();

//            String district = location.getDistrict();    //获取区县
            //获取街道信息
            street = location.getStreet();

            publishAddressTv.setText(city + location.getDistrict() + street + location.getStreetNumber());

            mLocationClient.stop();
        }
    }

    private void showTakePhotoOrAlbumDialog() {
        TDialog tDialog = new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.take_photos_dialog_layout)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.BOTTOM)
                .addOnClickListener(R.id.tv_open_camera, R.id.tv_open_album, R.id.tv_cancel)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.tv_open_camera:
                                FunctionConfig camera = new FunctionConfig.Builder()
                                        .setEnableEdit(true)
                                        .setEnableCrop(true)
                                        .setEnableRotate(true)
                                        .build();
                                //带配置
                                GalleryFinal.openCamera(300, camera, new GalleryFinal.OnHanlderResultCallback() {
                                    @Override
                                    public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                                        if (reqeustCode == 300) {
                                            for (int i = 0; i < resultList.size(); i++) {
                                                if (imageList.size() < 3) {
                                                    imageList.add(new File(resultList.get(i).getPhotoPath()));
                                                    final View view = layoutInflater.inflate(R.layout.item_image, null);
                                                    view.setTag(imageList.get(i));
                                                    photoLl.addView(view);
                                                    ImageView photo = view.findViewById(R.id.photo);
                                                    Glide.with(PublishActivity.this)
                                                            .load(resultList.get(i).getPhotoPath())
                                                            .into(photo);
                                                    photo.setOnClickListener(new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View v) {
                                                            AlertDialog.Builder builder = new AlertDialog.Builder(PublishActivity.this);
                                                            builder.setTitle("温馨提示");
                                                            builder.setMessage("你确定要删除此图片吗?");
                                                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    Log.e("finali", view.getTag() + "");
                                                                    photo_num = photo_num + 1;
                                                                    imageList.remove(view.getTag());
                                                                    photoLl.removeView(view);
                                                                    dialog.dismiss();
                                                                    addcommentImgTv.setVisibility(View.VISIBLE);
                                                                }
                                                            });
                                                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    dialog.dismiss();
                                                                }
                                                            });
                                                            //参数都设置完成了，创建并显示出来
                                                            builder.create().show();
                                                        }
                                                    });
                                                }

                                            }
                                            if (imageList.size() == 3) {
                                                addcommentImgTv.setVisibility(View.GONE);
                                            }
                                            photo_num = photo_num - resultList.size();
                                        }
                                    }

                                    @Override
                                    public void onHanlderFailure(int requestCode, String errorMsg) {

                                    }
                                });
                                tDialog.dismiss();
                                break;
                            case R.id.tv_open_album:
                                FunctionConfig album = new FunctionConfig.Builder()
                                        .setEnableEdit(true)
                                        .setEnableCrop(true)
                                        .setEnableRotate(true)
                                        .setEnablePreview(true)
                                        .setMutiSelectMaxSize(photo_num)
                                        .build();
                                //带配置
                                GalleryFinal.openGalleryMuti(200, album, new GalleryFinal.OnHanlderResultCallback() {
                                    @Override
                                    public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                                        if (reqeustCode == 200) {
                                            for (int i = 0; i < resultList.size(); i++) {
                                                if (imageList.size() < 3) {
                                                    imageList.add(new File(resultList.get(i).getPhotoPath()));
                                                    final View view = layoutInflater.inflate(R.layout.item_image, null);
                                                    view.setTag(imageList.get(i));
                                                    photoLl.addView(view);
                                                    ImageView photo = view.findViewById(R.id.photo);
                                                    Glide.with(PublishActivity.this)
                                                            .load(resultList.get(i).getPhotoPath())
                                                            .into(photo);
                                                    photo.setOnClickListener(new View.OnClickListener() {
                                                        @Override
                                                        public void onClick(View v) {
                                                            AlertDialog.Builder builder = new AlertDialog.Builder(PublishActivity.this);
                                                            builder.setTitle("温馨提示");
                                                            builder.setMessage("你确定要删除此图片吗?");
                                                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    photo_num = photo_num + 1;
                                                                    Log.e("finali", view.getTag() + "");
                                                                    imageList.remove(view.getTag());
                                                                    photoLl.removeView(view);
                                                                    dialog.dismiss();
                                                                    addcommentImgTv.setVisibility(View.VISIBLE);
                                                                }
                                                            });
                                                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                                @Override
                                                                public void onClick(DialogInterface dialog, int which) {
                                                                    dialog.dismiss();
                                                                }
                                                            });
                                                            //参数都设置完成了，创建并显示出来
                                                            builder.create().show();
                                                        }
                                                    });
                                                }

                                            }
                                            if (imageList.size() == 3) {
                                                addcommentImgTv.setVisibility(View.GONE);
                                            }
                                            photo_num = photo_num - resultList.size();
                                        }
                                    }

                                    @Override
                                    public void onHanlderFailure(int requestCode, String errorMsg) {

                                    }
                                });
                                tDialog.dismiss();
                                break;
                            case R.id.tv_cancel:

                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();
    }

}
